package com.weixin.paleituo.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.MainPagerAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UserInfoBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.ExitLoginSuccess;
import com.weixin.paleituo.eventbus.LoginMessageEvent;
import com.weixin.paleituo.eventbus.UpdataInfoEvent;
import com.weixin.paleituo.fragment.HomeFragment;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.AesUtil;
import com.weixin.paleituo.util.DeviceUuidFactory;
import com.weixin.paleituo.util.FileUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AppVersionUpdate;
import com.weixin.paleituo.view.ForbidScrollViewpager;
import com.weixin.paleituo.view.VersionUpdatePopuwindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.viewpager_activity_main)
    public ForbidScrollViewpager mViewPager;
    @BindView(R.id.rg_tab_bar)
    public RadioGroup mRadioGroup;
    @BindView(R.id.rb_wuye)
    RadioButton mRbService;
    @BindView(R.id.rb_shared_house)
    RadioButton mRbSharedHouse;
    @BindView(R.id.rb_shequan)
    RadioButton mRbShequan;
    @BindView(R.id.rb_my)
    RadioButton mRbMy;
    private MainPagerAdapter mMainPagerAdapter;
    @BindView(R.id.rb_home)
    public RadioButton mHomeRadioButton;
    public final static int SCANNIN_GREQUEST_CODE = 1001;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
            Manifest.permission.CAMERA,//相机
            Manifest.permission.RECORD_AUDIO,//相机
            Manifest.permission.ACCESS_COARSE_LOCATION,//定位
            Manifest.permission.ACCESS_FINE_LOCATION,//定位
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE

    };

    IntentFilter mFilter = new IntentFilter() {
        {
            addAction("android.net.conn.CONNECTIVITY_CHANGE");
            addAction("android.net.wifi.WIFI_STATE_CHANGED");
            addAction("android.net.wifi.STATE_CHANGE");

        }
    };
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                ConnectivityManager manager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                Log.i(TAG, "CONNECTIVITY_ACTION");

                NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
                if (activeNetwork != null) { // connected to the internet
                    if (activeNetwork.isConnected()) {
                        if (mLocationClient != null) {
                            mLocationClient.start();
                        }
                        //上线
                        if (!BaseApplication.isLoginSuccess) {
                            login();


                        }

                    } else {
                        Log.e(TAG, "当前没有网络连接，请确保你已经打开网络 ");

                        if (mLocationClient != null) {

                            mLocationClient.stop();
                        }
                        //下线
                        EventBus.getDefault().post(new ExitLoginSuccess());
                        BaseApplication.isLoginSuccess = false;
                      //  BaseApplication.sUserInfoBean = null;

                    }

                } else {   // not connected to the internet
                    Log.e(TAG, "当前没有网络连接，请确保你已经打开网络 ");
                    if (mLocationClient != null) {
                        mLocationClient.stop();

                    }
                    //下线
                    EventBus.getDefault().post(new ExitLoginSuccess());
                    BaseApplication.isLoginSuccess = false;
                 //   BaseApplication.sUserInfoBean = null;

                }

            }

        }
    };
    private AppVersionUpdate mAppVersionUpdate;

    /**
     * 登录
     */
    private void login() {

        //登录
        String userName = PreferencesUtils.getInstance().getString(Contans.username, "");
        String password = PreferencesUtils.getInstance().getString(Contans.password, "");
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)) {
            Observable<StatusCode<UserInfoBean>> loginObserver = ApiUtils.getApi().login(Contans.isEncrypt?AesUtil.aesEncrypt(userName):userName,Contans.isEncrypt? AesUtil.aesEncrypt(password):password, DeviceUuidFactory.getInstance(MainActivity.this).getDeviceUuid());
            HttpUtil.getInstance().toSubscribe(loginObserver, new ProgressSubscriber<UserInfoBean>(MainActivity.this) {

                @Override
                protected void _onNext(StatusCode<UserInfoBean> t) {
                    UserInfoBean userInfoBean = t.getData();
                    if (userInfoBean != null) {
                        BaseApplication.isLoginSuccess = true;
                        BaseApplication.sUserInfoBean = userInfoBean;

                        EventBus.getDefault().post(new LoginMessageEvent(userInfoBean));
                    } else {
                        ToastUtils.makeText(t.getDetailMsg() + "");
                    }

                }

                @Override
                protected void _onError(String message) {

                    ToastUtils.makeText("登录失败");

                    BaseApplication.isLoginSuccess = false;
                  //  BaseApplication.sUserInfoBean = null;


                }
            }, "", lifecycleSubject, false, true);

        }
    }


    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        // mViewPager = findViewById(R.id.viewpager_activity_main);
        //mRadioGroup = findViewById(R.id.rg_tab_bar);
        //mHomeRadioButton = findViewById(R.id.rb_home);
        LogUtils.i(TAG, Build.VERSION.SDK_INT + "");
        /*if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();*/

        //UIUtils.showFullScreen(this);
       // int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        //LogUtils.i(TAG, "Max memory is " + maxMemory + "KB");
    }


    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        initPerssionData();
        initPerssionEvent();
   /*     if (!UIUtils.isMarshmallow()) {
            initPerssionData();
            initPerssionEvent();
            creatDir();
        } else {
            CheckPermission checkPermission = new CheckPermission(this);
            if (checkPermission.permissionSet(PERMISSION)) {
                startPermissionActivity();
            } else {
                initPerssionData();
                initPerssionEvent();
                creatDir();
            }
        }*/


    }

    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, Contans.PERMISSION_REQUST_COND, PERMISSION);
    }


    private void initPerssionEvent() {
    }

    private void initPerssionData() {

        mMainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
        mViewPager.setOffscreenPageLimit(5);
        mViewPager.setAdapter(mMainPagerAdapter);
        mViewPager.setCurrentItem(0);
        mHomeRadioButton.setChecked(true);
        getAndroiodScreenProperty();
        onCreate();
        registerReceiver(mBroadcastReceiver, mFilter);
        UIUtils.showFullScreen(MainActivity.this,false);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                if (position==4){
                    UIUtils.showFullScreen(MainActivity.this,true);
                }else {
                    UIUtils.showFullScreen(MainActivity.this,false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        int intExtra = intent.getIntExtra(Contans.INTENT_EXTRA, 0);
        switch (intExtra) {
            case 0:
                mViewPager.setCurrentItem(0,false);
                mHomeRadioButton.setChecked(true);
                UIUtils.showFullScreen(MainActivity.this,false);
                break;
            case 1:
                mViewPager.setCurrentItem(1,false);

                mRbShequan.setChecked(true);
                UIUtils.showFullScreen(MainActivity.this,false);
                break;
            case 2:
                mViewPager.setCurrentItem(2,false);
                mRbSharedHouse.setChecked(true);
                UIUtils.showFullScreen(MainActivity.this,false);
                break;
            case 3:
                mViewPager.setCurrentItem(3,false);
                mRbService.setChecked(true);
                UIUtils.showFullScreen(MainActivity.this,false);
                break;
            case 4:
                mViewPager.setCurrentItem(4,false);
                mRbMy.setChecked(true);
                UIUtils.showFullScreen(MainActivity.this,true);
                break;
        }

    }

    /**
     * 去商城
     * @selectPositon 0 首页 1 商城 2 共享家 3 物业 4 我的
     * @param context
     */
    public static void goGoodsShop(Context context, int selectPositon) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(Contans.INTENT_EXTRA, selectPositon);
        context.startActivity(intent);
    }


    //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
    //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文中的说明
    public void onCreate() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(0);
        option.setIsNeedAddress(true);
        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

    }

    public void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)


        Log.d("h_bl", "屏幕宽度（像素）：" + width);
        Log.d("h_bl", "屏幕高度（像素）：" + height);
        Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
        Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
        Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
        Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);
    }

    @Override
    protected void initEvent() {
        mRadioGroup.setOnCheckedChangeListener(this);


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updataPersonInfo(UpdataInfoEvent updataInfoEvent) {
        //去登陆
        login();

    }


    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId) {
            case R.id.rb_home:
                mViewPager.setCurrentItem(0, false);

                break;
            case R.id.rb_shequan:
                mViewPager.setCurrentItem(1, false);
                break;

            case R.id.rb_shared_house:
                mViewPager.setCurrentItem(2, false);
                break;

            case R.id.rb_wuye:
                mViewPager.setCurrentItem(3, false);
                //  group.check(mCheckId);

                //   FloorHomeActivity.startActivity(this);
                break;
            case R.id.rb_my:
                mViewPager.setCurrentItem(4, false);
                break;
        }
    }

    @OnClick({R.id.Iv_home_bg})
    public void onclick(){
        mRbSharedHouse.setChecked(true);
    }

    private int number = 1;

    public class MyLocationListener extends BDAbstractLocationListener {

        private HomeFragment mHomeFragment;

        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            LogUtils.i(TAG, "number :" + number++);
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            LogUtils.i(TAG, "获取详细地址信息 :" + addr);
            LogUtils.i(TAG, "获取国家 :" + country);
            LogUtils.i(TAG, "获取省份 :" + province);
            LogUtils.i(TAG, "获取城市 :" + city);
            LogUtils.i(TAG, "获取区县 :" + district);
            LogUtils.i(TAG, "获取街道信息 :" + street);
            LogUtils.i(TAG, "定位半径" + location.getRadius());
            LogUtils.i(TAG, location.toString());
            LogUtils.i(TAG, location.getLocType() + "");

            if (!StringUtils.isEmpty(city)){

                PreferencesUtils.getInstance().putString(Contans.CITY,city);
                mHomeFragment = (HomeFragment) mMainPagerAdapter.getItem(0);
                mHomeFragment.setLocationCity(city);
                mHomeFragment.setLocationLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
                BaseApplication.sLocationCity = city;

            }

            //   LogUtils.i(TAG,BaseApplication.sUserInfoBean.toString());

        }
    }

    /*@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Contans.PERMISSION_REQUST_COND) {
            if (resultCode == PermissionActivity.PERMISSION_DENIEG) {
                //没有权限
                finish();
            } else if (resultCode == PermissionActivity.PERMISSION_GRANTED) {
                //有权限
                initPerssionData();
                initPerssionEvent();
                creatDir();
            }
        }
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if (mAppVersionUpdate != null) {
            VersionUpdatePopuwindow popu = mAppVersionUpdate.getPopu();
            if (popu == null || !popu.isShowing()) {
                long currentTime = System.currentTimeMillis();
                if ((currentTime - exitTime) < 2000) {
                    Process.killProcess(Process.myPid());
                    System.exit(0);
                    super.onBackPressed();
                } else {
                    Toast.makeText(this, R.string.double_click_exit, Toast.LENGTH_SHORT).show();
                    exitTime = currentTime;
                }
            }
        } else {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - exitTime) < 2000) {
                super.onBackPressed();
            } else {
                Toast.makeText(this, R.string.double_click_exit, Toast.LENGTH_SHORT).show();
                exitTime = currentTime;
            }
        }

    }

    /**
     * 创建目录
     */
    private void creatDir() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            FileUtils.APP_DIR = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/paleituo";
        } else {
            FileUtils.APP_DIR = this.getFilesDir().getAbsolutePath() + "/paleituo";
        }
        FileUtils.APP_LOG = FileUtils.APP_DIR + "/log";
        FileUtils.APP_CRASH = FileUtils.APP_DIR + "/crash";
        FileUtils.APK_DIR = FileUtils.APP_DIR + "/apks";
        FileUtils.IMAGE_DIR = FileUtils.APP_DIR + "/imag";

        File appDir = new File(FileUtils.APP_DIR);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File logDir = new File(FileUtils.APP_LOG);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File crashDir = new File(FileUtils.APP_CRASH);
        if (!crashDir.exists()) {
            crashDir.mkdirs();
        }
        File apkDir = new File(FileUtils.APK_DIR);
        if (!apkDir.exists()) {
            apkDir.mkdirs();
        }
        File imageDir = new File(FileUtils.IMAGE_DIR);
        if (!imageDir.exists()) {
            imageDir.mkdirs();
        }

        //检查版本更新
        mAppVersionUpdate = new AppVersionUpdate(this, mViewPager, lifecycleSubject);
        mAppVersionUpdate.checkVersionUpdate(true);

        //上传错误日志


        final File logfile=new File(FileUtils.APP_CRASH,"log.txt");

        if (logfile.exists()){

        //
            // FileUtils.APP_CRASH/
            Observable<StatusCode<String>> statusCodeObservable = Observable.just(logfile)
                    .flatMap(new Function<File, ObservableSource<StatusCode<String>>>() {
                @Override
                public ObservableSource<StatusCode<String>> apply(File file) throws Exception {
                    InputStream inputStream = new FileInputStream(file);
                    String s = FileUtils.readInStream(inputStream);

                    if (StringUtils.isEmpty(s)) {
                        return Observable.empty();
                    }

                    return ApiUtils.getApi().uploadErrLog(s, 1);
                }
            }).subscribeOn(Schedulers.io());

            HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<String>(this) {
                @Override
                protected void _onNext(StatusCode<String> stringStatusCode) {
                    LogUtils.i(TAG,"成功");
                    FileUtils.deleteFile(logfile.getAbsolutePath());
                }

                @Override
                protected void _onError(String message) {

                    LogUtils.i(TAG,"上传错误日志失败");

                }
            },"",lifecycleSubject,false,true);

        }


        //注册微信
       /* WXTextObject wxTextObject=new WXTextObject();
        wxTextObject.text="hehe";

        WXMediaMessage wxMediaMessage=new WXMediaMessage();
        wxMediaMessage.mediaObject=wxTextObject;
        wxMediaMessage.description="haha";

        SendMessageToWX.Req req =new SendMessageToWX.Req();
        req.transaction=String.valueOf(SystemClock.currentThreadTimeMillis());
        req.message=wxMediaMessage;

        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, WXPayEntry.APP_ID);

        wxapi.sendReq(req);*/

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);



    }
}
